#include <webx/menu.h>
#include <dbentity/T_XG_CONF.h>

class EditNote : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(EditNote, "/confile/${filename}")

int EditNote::process()
{
	param_string(id);
	param_string(flag);
	param_string(icon);
	param_string(level);
	param_string(title);
	param_string(folder);
	param_string(remark);
	param_string(content);
	param_string(deficon);

	webx::CheckAlnumString(id, 0);
	webx::CheckFileName(title, 0);
	webx::CheckFileName(folder, 0);

	if (deficon.empty()) deficon = "/res/img/note/code.png";

	checkLogin();

	int res = 0;
	string sqlcmd;
	CT_XG_CONF tab;
	sp<DBConnect> dbconn = webx::GetDBConnect(dbid);

	tab.init(dbconn);
	tab.id = id;

	if (flag == "A" || flag == "C" || flag == "R")
	{
		string name = folder;

		if ((flag == "A" && title.empty()) || (flag == "C" && stdx::tolower(name) == "WEBPAGE")) return simpleResponse(XG_PARAMERR);

		if (icon.empty())
		{
			if (flag == "C")
			{
				icon = "/res/img/menu/folder.png";
			}
			else
			{
				icon = deficon;
			}
		}

		if (flag == "R")
		{
			stdx::format(sqlcmd, "USER='%s' AND FOLDER='%s'", user.c_str(), folder.c_str());
			
			res = tab.remove(sqlcmd);
		}
		else
		{
			sp<RowData> row;
			sp<QueryResult> rs;

			stdx::format(sqlcmd, "SELECT COUNT(*) FROM T_XG_CONF WHERE USER='%s'", user.c_str());

			if (!(rs = dbconn->query(sqlcmd))) return simpleResponse(XG_SYSERR);

			if ((row = rs->next()) && row->getInt(0) > 1000) return simpleResponse(XG_AUTHFAIL);

			if (level.empty()) level = "1";

			tab.user = user;
			tab.icon = icon;
			tab.level = level;
			tab.title = title;
			tab.folder = folder;
			tab.remark = remark;
			tab.content = content;
			tab.statetime.update();

			for (int i = 0; i < 5; i++)
			{
				tab.id = DateTime::GetBizId();
				tab.position = (int)(time(NULL));

				if ((res = tab.insert()) >= 0) break;
			}

			if (res > 0)
			{
				json["statetime"] = tab.statetime.toString();
				json["icon"] = tab.icon.toString();
				json["id"] = tab.id.val();
			}
		}
	}
	else if (flag == "D")
	{
		res = XG_NOTFOUND;

		if (!tab.find()) return simpleResponse(XG_SYSERR);

		if (tab.next() && user == tab.user.val())
		{
			res = tab.remove();
		}
	}
	else if (flag == "U")
	{
		res = XG_NOTFOUND;

		if (!tab.find()) return simpleResponse(XG_SYSERR);
	
		if (tab.next() && user == tab.user.val())
		{
			if (icon.length() > 0) tab.icon = icon;
			if (level.length() > 0) tab.level = level;
			if (title.length() > 0) tab.title = title;
			if (folder.length() > 0) tab.folder = folder;
			if (remark.length() > 0) tab.remark = remark;

			if (tab.position.val() == 0) tab.position = (int)(time(NULL));

			if (content.empty() > 0)
			{
				content = tab.content.toString();
			}
			else
			{
				tab.content = content;
			}
			
			tab.statetime.update();

			if ((res = tab.update()) < 0) return simpleResponse(res);

			string tmp = tab.icon.toString();
			
			if (tmp.length() < 128) json["icon"] = tmp;
		}
	}
	else if (flag == "M")
	{
		res = XG_SYSERR;

		param_string(direct);

		while (true)
		{
			sp<RowData> row;
			vector<string> vec;
			sp<QueryResult> rs;
				
			stdx::format(sqlcmd, "SELECT MIN(ID),MAX(ID),COUNT(1) AS NUM FROM T_XG_CONF WHERE USER='%s' GROUP BY POSITION HAVING NUM>1", user.c_str());

			if (rs = dbconn->query(sqlcmd))
			{
				int position = time(NULL) - rand() % 100000000 - 1;

				while (row = rs->next())
				{
					stdx::format(sqlcmd, "UPDATE T_XG_CONF SET POSITION=%d WHERE ID='%s'", position, row->getString(0).c_str());
					vec.push_back(sqlcmd);

					stdx::format(sqlcmd, "UPDATE T_XG_CONF SET POSITION=%d WHERE ID='%s'", position - rand() % 1000000 - 1, row->getString(1).c_str());
					vec.push_back(sqlcmd);
				}
				
				for (string& sqlcmd : vec)
				{
					if (dbconn->execute(sqlcmd) < 0)
					{
						vec.clear();

						break;
					}
				}
			}

			if (vec.empty()) break;
		}

		if (id.length() > 0)
		{
			if (tab.find() && tab.next())
			{
				folder = tab.folder.val();

				int srcpos = tab.position.val();

				if (direct == "U")
				{
					stdx::format(sqlcmd, "USER='%s' AND FOLDER='%s' AND POSITION<%d AND LENGTH(TITLE)>0 ORDER BY POSITION DESC", user.c_str(), folder.c_str(), srcpos);
				}
				else
				{
					stdx::format(sqlcmd, "USER='%s' AND FOLDER='%s' AND POSITION>%d AND LENGTH(TITLE)>0 ORDER BY POSITION ASC", user.c_str(), folder.c_str(), srcpos);
				}

				if (tab.find(sqlcmd))
				{
					int destpos = srcpos;

					if (tab.next()) destpos = tab.position.val();

					if (srcpos == destpos)
					{
						stdx::format(sqlcmd, "UPDATE T_XG_CONF SET POSITION=POSITION%s WHERE ID='%s'", direct == "U" ? "-1" : "+1", id.c_str());

						res = dbconn->execute(sqlcmd);
					}
					else
					{
						stdx::format(sqlcmd, "UPDATE T_XG_CONF SET POSITION=%d WHERE USER='%s' AND FOLDER='%s' AND ID='%s' AND LENGTH(TITLE)>0 AND POSITION=%d", destpos, user.c_str(), folder.c_str(), id.c_str(), srcpos);
						
						if ((res = dbconn->execute(sqlcmd)) >= 0)
						{
							stdx::format(sqlcmd, "UPDATE T_XG_CONF SET POSITION=%d WHERE USER='%s' AND FOLDER='%s' AND ID<>'%s' AND LENGTH(TITLE)>0 AND POSITION=%d", srcpos, user.c_str(), folder.c_str(), id.c_str(), destpos);

							res = dbconn->execute(sqlcmd);
						}
					}
				}
			}
		}
		else if (folder.length() > 0)
		{
			stdx::format(sqlcmd, "USER='%s' AND FOLDER='%s' AND (TITLE IS NULL OR TITLE='')", user.c_str(), folder.c_str());

			if (tab.find(sqlcmd) && tab.next())
			{
				int srcpos = tab.position.val();

				if (direct == "U")
				{
					stdx::format(sqlcmd, "USER='%s' AND POSITION<%d AND (TITLE IS NULL OR TITLE='') ORDER BY POSITION DESC", user.c_str(), srcpos);
				}
				else
				{
					stdx::format(sqlcmd, "USER='%s' AND POSITION>%d AND (TITLE IS NULL OR TITLE='') ORDER BY POSITION ASC", user.c_str(), srcpos);
				}

				if (tab.find(sqlcmd))
				{
					int destpos = srcpos;

					if (tab.next()) destpos = tab.position.val();

					if (srcpos == destpos)
					{
						stdx::format(sqlcmd, "UPDATE T_XG_CONF SET POSITION=POSITION%s WHERE USER='%s' AND FOLDER='%s' AND (TITLE IS NULL OR TITLE='')", direct == "U" ? "-1" : "+1", user.c_str(), folder.c_str());

						res = dbconn->execute(sqlcmd);
					}
					else
					{
						stdx::format(sqlcmd, "UPDATE T_XG_CONF SET POSITION=%d WHERE USER='%s' AND FOLDER='%s' AND (TITLE IS NULL OR TITLE='') AND POSITION=%d", destpos, user.c_str(), folder.c_str(), srcpos);
						
						if ((res = dbconn->execute(sqlcmd)) >= 0)
						{
							stdx::format(sqlcmd, "UPDATE T_XG_CONF SET POSITION=%d WHERE USER='%s' AND FOLDER<>'%s' AND (TITLE IS NULL OR TITLE='') AND POSITION=%d", srcpos, user.c_str(), folder.c_str(), destpos);

							res = dbconn->execute(sqlcmd);
						}
					}
				}
			}
		}
	}
	else
	{
		res = XG_PARAMERR;
	}

	if (res >= 0)
	{
		sp<Session> session = webx::GetLocaleSession("SYSTEM_CONFILE");

		if (session) session->clear();

		webx::ReloadSystemConfig();
	}

	json["code"] = res;
	out << json;

	return XG_OK;
}